// 登录页面组件

import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { authApi } from '../api/auth';
import type { LoginRequest } from '../types/auth';
import { useAuth } from '../contexts/AuthContext';
import { handleApiError, getErrorMessage } from '../utils/errorHandler';
import './LoginPage.css';

const LoginPage: React.FC = () => {
  const { login, isAuthenticated } = useAuth();
  const navigate = useNavigate();
  // 表单状态
  const [formData, setFormData] = useState<LoginRequest>({
    usernameOrEmail: '',
    password: '',
  });
  
  // 加载状态
  const [loading, setLoading] = useState(false);
  
  // 错误信息
  const [error, setError] = useState('');
  
  // 显示密码状态
  const [showPassword, setShowPassword] = useState(false);

  // 如果用户已登录，重定向到首页
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/', { replace: true });
    }
  }, [isAuthenticated, navigate]);

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
    // 清除错误信息
    if (error) {
      setError('');
    }
  };

  // 表单验证
  const validateForm = (): boolean => {
    if (!formData.usernameOrEmail.trim()) {
      setError('请输入用户名或邮箱');
      return false;
    }
    if (!formData.password.trim()) {
      setError('请输入密码');
      return false;
    }
    if (formData.password.length < 6) {
      setError('密码长度不能少于6位');
      return false;
    }
    return true;
  };

  // 处理登录提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await authApi.login(formData);
      
      if (response.code === 0) {
        // 登录成功，使用认证上下文更新状态
        login(response.data.accessToken, response.data.user);
        
        console.log('登录成功:', response.data.user);
        
        // 登录成功后跳转到首页
        navigate('/', { replace: true });
      } else {
        setError(response.message || '登录失败');
      }
    } catch (err) {
      console.error('登录错误:', err);
      
      // 使用统一的错误处理
      handleApiError(err);
      
      // 设置用户友好的错误信息
      const errorMessage = getErrorMessage(err);
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-page">
      <div className="login-container">
        <div className="login-header">
          <h1 className="login-title">足球管理系统</h1>
          <p className="login-subtitle">欢迎回来，请登录您的账户</p>
        </div>
        
        <form className="login-form" onSubmit={handleSubmit}>
          <div className="form-group">
            <label htmlFor="usernameOrEmail" className="form-label">
              用户名或邮箱
            </label>
            <input
              type="text"
              id="usernameOrEmail"
              name="usernameOrEmail"
              className="form-input"
              placeholder="请输入用户名或邮箱"
              value={formData.usernameOrEmail}
              onChange={handleInputChange}
              disabled={loading}
              autoComplete="username"
            />
          </div>
          
          <div className="form-group">
            <label htmlFor="password" className="form-label">
              密码
            </label>
            <div className="password-input-wrapper">
              <input
                type={showPassword ? 'text' : 'password'}
                id="password"
                name="password"
                className="form-input"
                placeholder="请输入密码"
                value={formData.password}
                onChange={handleInputChange}
                disabled={loading}
                autoComplete="current-password"
              />
              <button
                type="button"
                className="password-toggle"
                onClick={() => setShowPassword(!showPassword)}
                disabled={loading}
              >
                {showPassword ? '隐藏' : '显示'}
              </button>
            </div>
          </div>
          
          {error && (
            <div className="error-message">
              {error}
            </div>
          )}
          
          <button
            type="submit"
            className="login-button"
            disabled={loading}
          >
            {loading ? '登录中...' : '登录'}
          </button>
        </form>
        
        <div className="login-footer">
          <p className="footer-text">
            还没有账户？
            <Link to="/register" className="footer-link">立即注册</Link>
          </p>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;